package cn.cloudevops.mapdemo;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 实时向获取地理位置
 *
 * 时间间隔：1s
 */
public class MainActivity extends AppCompatActivity implements GeocodeSearch.OnGeocodeSearchListener {

    @BindView(R.id.startAddressEditor)
    EditText startAddressEditor;
    @BindView(R.id.endAddressEditor)
    EditText endAddressEditor;
    @BindView(R.id.routePlanButton)
    Button routePlanButton;
    @BindView(R.id.searchPlaceEditor)
    EditText searchPlaceEditor;
    @BindView(R.id.searchPlaceButton)
    Button searchPlaceButton;
    @BindView(R.id.startLocationButton)
    Button startLocationButton;

    public static final String LATITUDE = "latitude";
    public static final String LONGITUDE = "longitude";
    public static final String MARKER_TITLE = "markerTitle";
    public static final String MARKER_DETAIL = "markerDetail";
    public static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATIONS = 1;


    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = new AMapLocationClientOption();
    private static String TAG = "MainActivity";

    private GeocodeSearch geocoderSearch;

    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置显示的内容
        setContentView(R.layout.activity_main);
        setTitle(R.string.main_activity_title);

        ButterKnife.bind(this);

        initLocation();

        // 打印SHA1值
        Log.e(TAG, "sha1: " + Utils.getApkSha1(getApplicationContext()));

        // 搜索初始化
        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);

    }

    @OnClick(R.id.routePlanButton)
    void enterRoutePlanButton() {
        Log.e(TAG, "点击路线规划按钮");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 默认的定位参数
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);  // 可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);  // 可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);  // 可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(1000);  // 可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);  // 可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);  // 可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);  // 可选，设置是否等待wifi刷新，默认为false。如果设置为true，会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);  // 可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);  // 可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true);  // 可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true);  // 可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    /**
     * 初始化定位
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        //设置定位参数
        locationClient.setLocationOption(getDefaultOption());
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = loc -> {
        String msg;
        if (null != loc) {
            if (loc.getErrorCode() == 0) {
                msg = "经度: " + loc.getAltitude() + ", 纬度: " + loc.getLatitude() + ", 地址: " + loc.getAddress();
                Log.e(TAG, msg);
            } else {
                msg = "错误码: " + loc.getErrorCode();
                Log.e(TAG, msg);
            }
        } else {
            msg = "定位获取失败";
            Log.e(TAG, msg);
        }

//        MsgFragment msgFragment = MsgFragment.newInstance(msg);
//        FragmentManager manager = getSupportFragmentManager();
//        FragmentTransaction transaction = manager.beginTransaction();
//        transaction.add(msgFragment, TAG);

        // 停止定位
        stopLocation();
    };

    /**
     * 开始定位
     */
    private void startLocation() {
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     */
    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    /**
     * 销毁定位
     */
    private void destroyLocation() {
        if (null != locationClient) {
            // 如果AMapLocationClient是在当前Activity实例化的，
            // 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @OnClick(R.id.searchPlaceButton)
    public void searchPlaceButtonClicked() {
        Log.e(TAG, "点击搜索位置坐标按钮");
        // 第一个参数表示具体地址，第二个参数表示查询城市，可以是中文或者中文全拼、citycode、adcode
        GeocodeQuery query = new GeocodeQuery(searchPlaceEditor.getText().toString(), "深圳");
        geocoderSearch.getFromLocationNameAsyn(query);
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
        if (i == 1000) {
            // 解析result获取坐标信息
            Log.e(TAG, "搜索结果: " + geocodeResult.getGeocodeAddressList().size());
            for (GeocodeAddress geocodeAddress : geocodeResult.getGeocodeAddressList()) {
                Log.e(TAG, geocodeAddress.getLatLonPoint().toString());
                Log.e(TAG, geocodeAddress.getFormatAddress());
                Log.e(TAG, geocodeAddress.getAdcode());
                Log.e(TAG, geocodeAddress.getBuilding());
                Log.e(TAG, geocodeAddress.getCity());
                Log.e(TAG, geocodeAddress.getDistrict());
                Log.e(TAG, geocodeAddress.getLevel());
                Log.e(TAG, geocodeAddress.getNeighborhood());
                Log.e(TAG, geocodeAddress.getProvince());
                Log.e(TAG, geocodeAddress.getTownship());

                intent=new Intent(MainActivity.this, LocationActivity.class);
                intent.putExtra(MainActivity.LATITUDE, geocodeAddress.getLatLonPoint().getLatitude());
                intent.putExtra(MainActivity.LONGITUDE, geocodeAddress.getLatLonPoint().getLongitude());
                intent.putExtra(MainActivity.MARKER_TITLE, searchPlaceEditor.getText().toString());
                intent.putExtra(MainActivity.MARKER_DETAIL, geocodeAddress.getFormatAddress());
                startActivity(intent);
            }
        } else {
            Log.e(TAG, "地址搜索失败");
        }

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @OnClick(R.id.startLocationButton)
    public void startLocationButtonClicked() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            Log.e(TAG, "开始定位");
            MsgFragment.newInstance("开始定位");
            startLocation();
        } else {
            // Permission is not granted
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
            } else {
                // No explanation needed; request the permission
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATIONS);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATIONS: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Log.e(TAG, "获取位置权限成功");
                } else {
                    Log.e(TAG, "获取位置权限失败");
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
            }

            // other 'case' lines to check for other
            // permissions this app might request.
        }
    }
}
